<?php
// +----------------------------------------------------------------------
// | likeshop开源商城系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | gitee下载：https://gitee.com/likeshop_gitee
// | github下载：https://github.com/likeshop-github
// | 访问官网：https://www.likeshop.cn
// | 访问社区：https://home.likeshop.cn
// | 访问手册：http://doc.likeshop.cn
// | 微信公众号：likeshop技术社区
// | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用，未经许可不能去除前后端官方版权标识
// |  likeshop系列产品收费版本务必购买商业授权，购买去版权授权后，方可去除前后端官方版权标识
// | 禁止对系统程序代码以任何目的，任何形式的再发布
// | likeshop团队版权所有并拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeshop.cn.team
// +----------------------------------------------------------------------

namespace app\admin\logic;
use app\common\server\UrlServer;
use think\Db;
use think\Exception;

class GoodsLogic
{
    /*
     * 商品统计
     */
    public static function statistics(){
        // 回收站中商品
        $goods['recycle'] = Db::name('goods')->where(['del'=>0, 'status'=>-1])->count('id');
        // 下架商品
        $goods['warehouse'] = Db::name('goods')->where(['del'=>0, 'status'=>0])->count('id');

        // 销售中商品数量(含库存预警)
        $goods['sell'] = Db::name('goods')->where(['del'=>0, 'status'=>1])->count('id');

        // 仓库中、销售中的库存预警商品数量
//        $goods['warn'] = Db::name('goods')
//            ->where([
//                ['del', '=', 0],
//                ['stock_warn', '>', 0],
//                ['stock','exp', Db::raw('<stock_warn')]
//            ])->count();
        return $goods;
    }

    /*
     * 商品列表
     */
    public static function lists($get)
    {
        $where = [];
        $where[] = ['del', '=', '0'];


        if (isset($get['name']) && $get['name']) {
            $where[] = ['name', 'like', '%' . $get['name'] . '%'];
        }
        if(isset($get['type'])){
            $where[] = ['status','=',$get['type']];
        }
        
        $goods_count = Db::name('goods')
                ->where($where)
                ->count();
//        echo Db::name('goods')->getLastSql();
        $goods_list = Db::name('goods')
                ->where($where)
                ->page($get['page'], $get['limit'])
                ->order('id desc')
                ->select();



        foreach ($goods_list as &$item) {
            $item['create_time_desc'] = $item['create_time'];

            if($item['type']==1){
                $item['type_str'] = '主商品';
            }else{
                $item['type_str']='附属商品';
            }
            //-1-回收站；0-下架；1-上架
            switch ($item['status']) {
                case '-1':
                    $item['status_str'] = '回收站';
                    break;
                case '0':
                    $item['status_str'] = '下架';
                    break;
                case '1':
                    $item['status_str'] = '上架';
                    break;
                default:
                    $item['status_str'] = '其它';
                    break;
            }
//            $item['image'] = UrlServer::getFileUrl($item['image']);
        }

        return ['count' => $goods_count, 'list' => $goods_list];
    }

    /**
     * 列表导出
     * @param $get
     */
    public static function exportFile($get)
    {
        $where = [];
        $where[] = ['del', '=', '0'];
        if($get['type']){
            switch ($get['type']){
                case 1:     //销售中
                    $where[] = ['status','=',1];
                    break;
                case 2:     //仓库中
                    $where[] = ['status','=',0];
                    break;
                case 3:     //库存预警
                    $where[] = ['stock_warn','>',0];
                    $where[] = ['stock','exp', Db::raw('<stock_warn')];
                    break;
                case 4:     //回收站
                    $where[] = ['status','=',-1];
                    break;
            }
        }

        if (isset($get['keyword']) && $get['keyword']) {
            $where[] = ['name', 'like', '%' . $get['keyword'] . '%'];
        }
        if(isset($get['code']) && $get['code']){
            $where[] = ['code','like','%'.$get['code'].'%'];
        }
        if(isset($get['supplier_id']) && $get['supplier_id']){
            $where[] = ['supplier_id','=',$get['supplier_id']];
        }
        if(isset($get['category_id']) && $get['category_id']){
            $where[] = ['first_category_id|second_category_id|third_category_id','=',$get['category_id']];
        }

        $goods_list_export = Db::name('goods')
            ->where($where)
            ->field('*,virtual_sales_sum+sales_sum as total_sales_sum')
            ->order('id desc')
            ->select();

        $goods_category_list = Db::name('goods_category')->where(['del'=>0])->column('name','id');

        $exportTitle = ['商品名称', '商品分类', '是否开启分销', '一级佣金比例', '二级佣金比例', '三级佣金比例', 'SKU最低价', 'SKU最高价', '总库存', '总销量', '新品推荐', '好物优选', '猜你喜欢', '排序', '发布时间'];
        $exportExt = 'xls';
        $exportData = [];
        foreach($goods_list_export as $item) {
            $cateName = self::getCateName($goods_category_list, $item); // 商品分类
            $isCommission = $item['is_commission'] ? '开启' : '关闭';
            $firstRatio = $item['first_ratio'] > 0 ? $item['first_ratio'].'%' : 0;
            $secondRatio = $item['second_ratio'] > 0 ? $item['second_ratio'].'%' : 0;
            $threeRatio = $item['three_ratio'] > 0 ? $item['three_ratio'].'%' : 0;
//            $isNew = $item['is_new'] ? '是' : '否';
//            $isBest = $item['is_best'] ? '是' : '否';
//            $isLike = $item['is_like'] ? '是' : '否';
            $createTime = $item['create_time'];
            $exportData[] = [$item['name'], $cateName, $isCommission, $firstRatio, $secondRatio, $threeRatio, $item['min_price'], $item['max_price'], $item['stock'], $item['total_sales_sum'], /*$isNew, $isBest, $isLike,*/ $item['sort'], $createTime];
        }

        return ['exportTitle'=> $exportTitle, 'exportData' => $exportData, 'exportExt'=>$exportExt, 'exportName'=>'商品列表'.date('Y-m-d H:i:s')];
    }

    /*
     * 删除商品
     */
    public static function del($id)
    {

        $data = [
            'del' => 1,
            'update_time' => date('Y-m-d H:i:s',time())
        ];
        return Db::name('goods')->where(['del' => 0, 'id' => $id])->update($data);
    }
    /**
     * 添加商品
     * @param $post
     * @param $spec_lists
     * @return bool
     */
    public static function add($post)
    {

        try {
            $time = date('Y-m-d H:i:s',time());
            // 替换内容中图片地址
            $domain = UrlServer::getFileUrl('/');
            $post['content'] = str_replace($domain, '/', $post['content']);
            //写入主表
            $data = [
                'name'                      => $post['name'],
                'description'               => $post['description'],
                'type'                      => $post['type'],
                'price'                     => $post['price'],
                'image'                     => UrlServer::getFileUrl($post['image']),
                'content'                   => $post['content'],
                'is_new'                    => isset($post['is_new']) && $post['is_new'] == 'on' ? 1 : 0,
                'is_best'                   => isset($post['is_best']) && $post['is_best'] == 'on' ? 1 : 0,
                'is_like'                   => isset($post['is_like']) && $post['is_like'] == 'on' ? 1 : 0,
                'create_time'               => $time
            ];
            $goods_id = Db::name('goods')->insertGetId($data);
            return true;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }


    /**
     * 编辑商品
     * @param $post
     * @param $spec_lists
     * @return bool
     */
    public static function edit($post)
    {

        try {
            $time = date('Y-m-d H:i:s',time());
            //写入主表
            $data = [
                'name'                      => $post['name'],
                'description'               => $post['description'],
                'type'                      => $post['type'],
                'price'                     => $post['price'],
                'image'                     => UrlServer::getFileUrl($post['image']),
                'content'                   => $post['content'],
//                'is_new'                    => isset($post['is_new']) && $post['is_new'] == 'on' ? 1 : 0,
//                'is_best'                   => isset($post['is_best']) && $post['is_best'] == 'on' ? 1 : 0,
//                'is_like'                   => isset($post['is_like']) && $post['is_like'] == 'on' ? 1 : 0,
                'update_time'               => $time
            ];

            Db::name('goods')
                ->where(['id' => $post['goods_id']])
                ->update($data);

            return true;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    /*
     * 商品信息
     */
    /**
     * 获取商品信息
     * @param $goods_id
     * @return array
     */
    public static function info($goods_id)
    {

        $info['base'] = Db::name('goods')
            ->where(['id' => $goods_id])
            ->withAttr('content', function ($value){
                $preg = '/(<img .*?src=")[^https|^http](.*?)(".*?>)/is';
                $local_url = UrlServer::getFileUrl('/');
                return  preg_replace($preg, "\${1}$local_url\${2}\${3}",$value);
            })->find();
        $info['base']['image'] = UrlServer::getFileUrl($info['base']['image']);
        return $info;
    }

    /**
     * Notes: 上架 / 下架 商品
     * @author 张无忌(2021/1/11 14:35)
     * @param array $ids (要更新的数据ID)
     * @param int $type (类型[0=下架, 1=上架])
     * @return bool
     */
    public static function upperOrLower(array $ids, int $type=0)
    {
        if (empty($ids)) {
            return false;
        }

        try {

            if ($type == 0) {
                $res = Db::name('team_activity')->whereIn('goods_id', $ids)
                    ->where(['status' => 1])->find();
                if ($res) {
                    return '该商品正在参与拼团，请先关闭后才允许下架';
                }
            }

            $result = Db::name('goods')->whereIn('id', $ids)->update([
                'status'      => $type,
                'update_time' => date('Y-m-d H:i:s',time())
            ]);
            return $result ? true : '上架失败';
        } catch (\Exception $e) {
            return '上架失败';
        }
    }


    /**
     * Notes: 分类名称
     * @param $cates
     * @param $item
     * @author 段誉(2021/6/3 19:45)
     * @return mixed|string
     */
    public static function getCateName($cates, $item)
    {
        if(isset($cates[$item['third_category_id']])) {
            return $cates[$item['third_category_id']];
        }

        if(isset($cates[$item['second_category_id']])) {
            return $cates[$item['second_category_id']];
        }

        if(isset($cates[$item['first_category_id']])) {
            return $cates[$item['first_category_id']];
        }

        return '';
    }
}